package edu.tms.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.easymvc.annotation.Encoding;
import net.easymvc.annotation.Param;
import net.easymvc.core.Action;
import edu.tms.bean.LoginLog;
import edu.tms.bean.User;
import edu.tms.controller.common.CommonController;
import edu.tms.dao.LoginLogDaoImp;
import edu.tms.dao.UserDaoImp;
import edu.tms.security.Authorizer;
import edu.tms.security.Encrypt;

public class MainAction extends Action implements CommonController{
	private Encrypt encrypt = new Encrypt();
	private UserDaoImp dao = new UserDaoImp();
	
	/**
	 * 登录
	 */
	@Override
	@Encoding("utf-8")
	public String login(
			@Param("account")String account,
			@Param("password")String pwd,
			@Param("code")String code) {
		User user = null;
		try {
			//验证码判断，从session中取出验证码
			if(code == null) return "redirect:/login.html";
			String relCode = (String) getSession("code");
			if(relCode == null) return "ajax:请重新刷新网页";
			//忽略大小写判断验证码
			if(!relCode.equalsIgnoreCase(code)) return "ajax:验证码错误";
			//从数据库中查询用户
			user = dao.findByKey(account);
			if(user == null) return "ajax:用户不存在";
			//使用MD5解码并匹配
			if(encrypt.checkpassword(pwd, user.getPassword())){
				//用户与密码皆对应，添加至登录日志
				LoginLogDaoImp loginDao = new LoginLogDaoImp();
				LoginLog log = new LoginLog();
				log.setCharId(user.getUserId());
				//获取登录ip
				log.setLoginIp(getIpAddr(getRequest()));
				log.setLoginTime(new Date());
				//获取上次登录时间
				user.setPrevLoginTime(loginDao.getPrevLoginTime(user.getUserId()));
				//身份认证
				Authorizer authorizer = new Authorizer();
				//获取导航栏
				String[] nav = authorizer.getNav(user);
				//获取职位权限
				String[] pos = authorizer.getPositions(user);
				if(nav == null || pos == null) return "ajax:权限获取失败 重新登录";
				//保存登录日志
				if(loginDao.save(log)!=0){
					setSession("curUser", user);
					//将用户对应导航存入session
					setSession("nav", nav);
					//将用户对应的职位权限存入session
					setSession("pos", pos);
				} else return "ajax:登录上传失败  重新登录";
				return "ajax:forword:/index.jsp";
			}
			return "ajax:密码错误";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/error.jsp";
	}
	
	/**
	 * 查找用户
	 * @param account
	 * @return
	 */
	@Encoding("utf-8")
	public String checkName(@Param("account") String account){
		try {
			User user = dao.findByKey(account);
			if(user == null){
				return "ajax:用户名不存在";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

	@Override
	@Encoding("utf-8")
	public String index() {
		return null;
	}

	/**
	 * 退出登录
	 */
	@Override
	public String logout() {
		setSession("curUser", null);
		return "redirect:/login.html";
	}

	/**
	 * 更改密码
	 */
	@Override
	@Encoding("utf-8")
	public String changePwd(
			@Param("oldPass")String oldPwd,
			@Param("password")String newPwd,
			@Param("cpassword")String newPwd1) {
		User user = (User) getSession("curUser");
		//用户为空
		if(user == null) return "redirect:/login.html";
		if(newPwd == null || newPwd1 == null || oldPwd == null || 
				newPwd.equals("") || newPwd1.equals("") || oldPwd.equals("")){
			setRequest("error_msg", "密码不能为空");
			return "redirect:/s/changepwd.jsp";
		}
		//密码不一致
		if(!newPwd.equals(newPwd1)){
			setRequest("error_msg", "密码不一致");
			return "redirect:/s/changepwd.jsp";
		}
		//TODO  网页中将密码转码？？
		try {
			//旧密码错误
			if(!encrypt.checkpassword(oldPwd, user.getPassword())){
				setRequest("error_msg", "密码错误");
				return "redirect:/s/changepwd.jsp";
			}
			//加密密码
			String pwdCode = encrypt.EncoderByMd5(newPwd);
			user.setPassword(pwdCode);
			if(dao.update(user)==1){
				return "/s/changepwd.jsp?error_msg=修改成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/s/changepwd.jsp?error_msg=修改失败";
	}

	/**
	 * 获取ip地址
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {  
	    String ip = null;  
	    String ipAddresses = request.getHeader("X-Forwarded-For");  
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {  
	        ipAddresses = request.getHeader("Proxy-Client-IP");  
	    }  
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {  
	        ipAddresses = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {  
	        ipAddresses = request.getHeader("HTTP_CLIENT_IP");  
	    }  
	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {  
	        ipAddresses = request.getHeader("X-Real-IP");  
	    }  
	    if (ipAddresses != null && ipAddresses.length() != 0) {  
	        ip = ipAddresses.split(",")[0];  
	    }  
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {  
	        ip = request.getRemoteAddr();  
	    } 
	    if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "本地";
        }
	    return ip;  
	}  

}
